<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>成语接龙游戏</title>
    <style>
        body {
            font-family: "Microsoft YaHei", sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background-color: white;
            border-radius: 10px;
            padding: 20px;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
        }
        h1 {
            text-align: center;
            color: #333;
        }
        #gameStatus {
            text-align: center;
            margin: 20px 0;
            font-size: 18px;
            padding: 10px;
            border-radius: 5px;
            background-color: #f0f8ff;
        }
        #history {
            height: 300px;
            border: 1px solid #ddd;
            border-radius: 5px;
            padding: 10px;
            margin-bottom: 20px;
            overflow-y: auto;
            background-color: #f9f9f9;
        }
        .history-item {
            margin: 10px 0;
            padding: 8px;
            border-radius: 5px;
            animation: fadeIn 0.5s ease-in-out;
        }
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        .bot {
            background-color: #e3f2fd;
            text-align: left;
            border-left: 4px solid #2196F3;
        }
        .user {
            background-color: #e8f5e9;
            text-align: right;
            border-right: 4px solid #4CAF50;
        }
        .input-area {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
        }
        #idiomInput {
            flex: 1;
            padding: 10px;
            font-size: 16px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }
        button {
            padding: 10px 20px;
            font-size: 16px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            transition: background-color 0.3s;
        }
        button:hover {
            background-color: #45a049;
        }
        #restartBtn {
            background-color: #2196F3;
        }
        #restartBtn:hover {
            background-color: #0b7dda;
        }
        .error {
            color: red;
            text-align: center;
            margin: 10px 0;
            height: 24px;
            line-height: 24px;
        }
        .loading {
            text-align: center;
            padding: 20px;
            color: #666;
        }
    </style>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // DOM元素
            const gameStatus = document.getElementById('gameStatus');
            const historyContainer = document.getElementById('history');
            const idiomInput = document.getElementById('idiomInput');
            const submitBtn = document.getElementById('submitBtn');
            const restartBtn = document.getElementById('restartBtn');
            const errorElement = document.querySelector('.error');

            // 游戏状态
            let currentIdiom = '';

            // 初始化游戏
            initGame();

            // 初始化游戏
            function initGame() {
                showLoading();
                fetch('/api/start')
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            currentIdiom = data.initial_idiom;
                            gameStatus.textContent = `游戏开始！机器人：${currentIdiom}`;
                            addHistoryItem('bot', currentIdiom);
                            clearError();
                        } else {
                            showError('游戏初始化失败，请刷新页面重试');
                        }
                    })
                    .catch(error => {
                        showError('连接服务器失败，请检查网络');
                        console.error('初始化错误:', error);
                    })
                    .finally(hideLoading);
            }

            // 提交成语
            submitBtn.addEventListener('click', function() {
                const userInput = idiomInput.value.trim();
                if (!userInput) {
                    showError('请输入成语');
                    return;
                }

                // 简单验证
                if (userInput.length !== 4) {
                    showError('成语必须是四个字');
                    return;
                }

                if (!/^[\u4e00-\u9fa5]+$/.test(userInput)) {
                    showError('成语必须由中文汉字组成');
                    return;
                }

                showLoading();
                clearError();

                fetch('/api/play', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ idiom: userInput })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        addHistoryItem('user', userInput);
                        addHistoryItem('bot', data.bot_idiom);
                        currentIdiom = data.bot_idiom;
                        gameStatus.textContent = `机器人：${currentIdiom}`;
                        idiomInput.value = '';
                    } else {
                        showError(data.error || '提交失败，请重试');
                    }
                })
                .catch(error => {
                    showError('提交失败，请检查网络连接');
                    console.error('提交错误:', error);
                })
                .finally(hideLoading);
            });

            // 再来一局 - 修复关键问题：调用restart接口而非start接口
            restartBtn.addEventListener('click', function() {
                if (confirm('确定要开始新游戏吗？当前进度将被重置')) {
                    showLoading();
                    historyContainer.innerHTML = '';
                    idiomInput.value = '';

                    // 调用restart接口获取新成语
                    fetch('/api/restart', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        }
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            currentIdiom = data.initial_idiom;
                            gameStatus.textContent = `游戏开始！机器人：${currentIdiom}`;
                            addHistoryItem('bot', currentIdiom);
                            clearError();
                        } else {
                            showError('重新开始失败，请刷新页面重试');
                        }
                    })
                    .catch(error => {
                        showError('重新开始失败，请检查网络');
                        console.error('重启错误:', error);
                    })
                    .finally(hideLoading);
                }
            });

            // 回车键提交
            idiomInput.addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    submitBtn.click();
                }
            });

            // 添加历史记录
            function addHistoryItem(role, content) {
                const item = document.createElement('div');
                item.className = `history-item ${role}`;
                item.textContent = content;
                historyContainer.prepend(item);

                // 滚动到底部
                historyContainer.scrollTop = historyContainer.scrollHeight;
            }

            // 显示错误
            function showError(message) {
                errorElement.textContent = message;
            }

            // 清除错误
            function clearError() {
                errorElement.textContent = '';
            }

            // 显示加载状态
            function showLoading() {
                gameStatus.textContent = '加载中...';
                submitBtn.disabled = true;
                restartBtn.disabled = true;
            }

            // 隐藏加载状态
            function hideLoading() {
                submitBtn.disabled = false;
                restartBtn.disabled = false;
            }
        });
    </script>
</head>
<body>
    <div class="container">
        <h1>成语接龙游戏</h1>
        <div id="gameStatus">游戏加载中...</div>
        <div id="history"></div>
        <div class="error"></div>
        <div class="input-area">
            <input type="text" id="idiomInput" placeholder="请输入四字成语">
            <button id="submitBtn">提交</button>
            <button id="restartBtn">再来一局</button>
        </div>
    </div>
</body>
</html>